package kercar.xmltools;
/**
 *  @author : jeffrey sambells
 *  @from : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
 */

import java.util.ArrayList;
import java.util.List;

import kercar.gps.GPSPosition;


public class polyPoints {

	/**
	 * read a polypoint and return the list of the points coded
	 * @param encoded
	 * @return 
	 */
	public static List<GPSPosition> decodePoly(String encoded) {

		List<GPSPosition> poly = new ArrayList<GPSPosition>();
		int index = 0, len = encoded.length();
		int lat = 0, lng = 0;

		while (index < len) {
			int b, shift = 0, result = 0;
			do {
				b = encoded.charAt(index++) - 63;
				result |= (b & 0x1f) << shift;
				shift += 5;
			} while (b >= 0x20);
			int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
			lat += dlat;

			shift = 0;
			result = 0;
			do {
				b = encoded.charAt(index++) - 63;
				result |= (b & 0x1f) << shift;
				shift += 5;
			} while (b >= 0x20);
			int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
			lng += dlng;

			//modification : In the original code position are in microdegree
			GPSPosition p = new GPSPosition((((double) lat / 1E5)),
                   (((double) lng / 1E5)));
			poly.add(p);
		}

		return poly;
	}
}
